
package com.fire.web.modules.all.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.*;
import com.fire.web.modules.all.mapper.*;
import com.fire.web.modules.all.request.AddBuildingReq;
import com.fire.web.modules.all.service.IBuildingService;
import com.fire.web.modules.all.utils.WrapperUtil;
import com.fire.web.modules.sys.entity.Role;
import com.fire.web.modules.sys.mapper.RoleMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 建筑物Service
 *
 * @author Matthew
 * @Date 2019-01-17 20:47
 */
@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, BuildingModel> implements IBuildingService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BuildingServiceImpl.class);

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private SequenceMapper sequenceMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private FireSupervisorMapper fireSupervisorMapper;

    @Autowired
    private FireSupervisorUserMapper fireSupervisorUserMapper;

    @Autowired
    private FireProprietorUserMapper fireProprietorUserMapper;

    @Autowired
    private FireMaintainUserMapper fireMaintainUserMapper;

    @Autowired
    private BuildingZoneMapper buildingZoneMapper;

    @Override
    public BuildingModel selectOne(BuildingModel entity){
        return buildingMapper.selectOne(entity);
    }

    @Override
    public List<BuildingModel>selectList(BuildingModel model){
        return buildingMapper.selectListByModel(model);
    }

    @Override
    public Page<BuildingModel> selectPage(int currentPage, int pageSize, Wrapper<BuildingModel> wrapper){
        return selectPage(new Page<BuildingModel>(currentPage,pageSize), wrapper);
    }

    @Override
    public Page<Map<String, Object>> selectMapsPage(int currentPage, int pageSize, Wrapper<BuildingModel> wrapper){
        return selectMapsPage(new Page<BuildingModel>(currentPage,pageSize), wrapper);
    }

    @Override
    public AjaxResult getBuildingItem(){
        List<Map> buildingItem = buildingMapper.getBuildingItem();
        return new AjaxResult(ErrorCodeConstants.SUCCESS, "获取下拉选成功", buildingItem, "获取下拉选成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBuilding(AddBuildingReq req, String userId) {
        if(StringUtils.isEmpty(req.getSupervisor())){
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("adminId",userId);
            List<FireSupervisorModel> supervisorlList = fireSupervisorMapper.selectList(wrapper);
            if(supervisorlList!=null && supervisorlList.size()>0){
                req.setSupervisor(supervisorlList.get(0).getSupervisorid());
            }

        }
        BuildingModel buildingModel = new BuildingModel();
        String building = sequenceMapper.getNextStringValue("building");
        buildingModel.setBuldingid(building);
        buildingModel.setAddress(req.getAddress());
        buildingModel.setBuildimageurl(req.getBuildimageurl());
        buildingModel.setBuildingname(req.getBuildingname());
        buildingModel.setCity(req.getCity());
        buildingModel.setCreatetime(new Date());
        buildingModel.setDistrict(req.getDistrict());
        buildingModel.setLatitude(req.getLatitude());
        buildingModel.setLevation(req.getLevation());
        buildingModel.setLongitude(req.getLongitude());
        buildingModel.setProvince(req.getProvince());
        buildingModel.setSupervisor(req.getSupervisor());
        buildingModel.setUpdatetime(new Date());
        buildingModel.setZone(req.getZone());
        // 新增地理编码表
        BuildingZoneModel buildingZoneModel = new BuildingZoneModel();
        String zoneId = sequenceMapper.getNextStringValue("zoneid");
        buildingZoneModel.setZoneid(zoneId);
        buildingZoneModel.setCreatetime(new Date());
        buildingZoneModel.setBuildingid(building);
        buildingZoneMapper.insert(buildingZoneModel);
        // 回填zoneid入building表
        buildingModel.setZoneid(zoneId);
        buildingMapper.insert(buildingModel);
        return new AjaxResult(ErrorCodeConstants.SUCCESS, "增加建筑物成功", buildingModel, "增加建筑物成功");
    }

    @Override
    public AjaxResult updateBuilding(AddBuildingReq req) {
        String buildingid = req.getBuldingid();
        if(StringUtils.isEmpty(buildingid)){
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "更新建筑物失败", "更新建筑物失败");
        }
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("buldingid",buildingid);
        BuildingModel buildingModel = new BuildingModel();
        buildingModel.setAddress(req.getAddress());
        buildingModel.setBuildimageurl(req.getBuildimageurl());
        buildingModel.setBuildingname(req.getBuildingname());
        buildingModel.setCity(req.getCity());
        buildingModel.setCreatetime(new Date());
        buildingModel.setDistrict(req.getDistrict());
        buildingModel.setLatitude(req.getLatitude());
        buildingModel.setLevation(req.getLevation());
        buildingModel.setLongitude(req.getLongitude());
        buildingModel.setProvince(req.getProvince());
        buildingModel.setSupervisor(req.getSupervisor());
        buildingModel.setUpdatetime(new Date());
        buildingModel.setZone(req.getZone());
        buildingModel.setZoneid(req.getZoneid());
        buildingMapper.update(buildingModel,wrapper);
        return new AjaxResult(ErrorCodeConstants.SUCCESS, "更新建筑物成功", buildingModel, "更新建筑物成功");
    }

    @Override
    public Page<Map<String, Object>> queryBuildingListMap(Page page, Wrapper wrapper, String username, String userId){
        String authority = "";
//        boolean isExists = false;
//        StringBuffer existsSqlStr = new StringBuffer("SELECT s.buildingid FROM t_mit_site s WHERE t.buldingid = s.buildingid");
        // admin
        String adminStr = "admin";
        if(!adminStr.equals(username)){
//            isExists = true;
//            List<Role> roleList = roleMapper.findRoleByUserId(userId);
//            if(roleList.size() > 0){
//                authority = roleList.get(0).getCode();
//            }
            Role role = roleMapper.findRoleByUserIdAndCode(userId,"supervisor");
            authority = role.getCode();
        }
        Wrapper unitWrapper = new EntityWrapper();
        unitWrapper.eq("adminid",userId);
        // supervisor监管单位
        String supervisorStr = "supervisor";
        if(supervisorStr.equals(authority)){
            List<FireSupervisorModel> supervisorModelList = fireSupervisorMapper.selectList(unitWrapper);
            wrapper.eq("supervisor",supervisorModelList.get(0).getSupervisorid());
//            existsSqlStr.append(" and (");
//            for(int i=0; i<supervisorUserModelList.size();i++){
//                FireSupervisorUserModel model = supervisorUserModelList.get(i);
//                existsSqlStr.append(" supervisorid='"+model.getSupervisor()+"'");
//                if(i!=supervisorUserModelList.size()-1){
//                    existsSqlStr.append(" or ");
//                }
//            }
//            existsSqlStr.append(")");
        }
//        // proprietor业主单位
//        String proprietorStr = "proprietor";
//        if(proprietorStr.equals(authority)){
//            List<FireProprietorUserModel> proprietorUserModelList = fireProprietorUserMapper.selectList(unitWrapper);
//            existsSqlStr.append(" and (");
//            for(int i=0; i<proprietorUserModelList.size();i++){
//                FireProprietorUserModel model = proprietorUserModelList.get(i);
//                existsSqlStr.append(" proprietor='"+model.getProprietor()+"'");
//                if(i!=proprietorUserModelList.size()-1){
//                    existsSqlStr.append(" or ");
//                }
//            }
//            existsSqlStr.append(")");
//        }
//        // maintainor维保单位
//        String maintainorStr = "maintainor";
//        if(maintainorStr.equals(authority)){
//            List<FireMaintainUserModel> maintainorUserModelList = fireMaintainUserMapper.selectList(unitWrapper);
//            existsSqlStr.append(" and (");
//            for(int i=0; i<maintainorUserModelList.size();i++){
//                FireMaintainUserModel model = maintainorUserModelList.get(i);
//                existsSqlStr.append(" maintainor='"+model.getMaintainor()+"'");
//                if(i!=maintainorUserModelList.size()-1){
//                    existsSqlStr.append(" or ");
//                }
//            }
//            existsSqlStr.append(")");
//        }
        wrapper = SqlHelper.fillWrapper(page, wrapper);
//        wrapper.exists(isExists,existsSqlStr.toString());
        page.setRecords(buildingMapper.queryBuildingListMap(page, wrapper));
        return page;
    }

}
